import MainRankItem from "./MainRankItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Start extends cc.Component {

    @property(cc.Node)
    mainNode: cc.Node = null;

    @property(cc.Prefab)
    itemNode: cc.Prefab = null;

    @property(cc.Prefab)
    mainInfoPrefab: cc.Prefab = null;

    @property(cc.Node)
    myNode: cc.Node = null;

    @property(cc.Node)
    rankMain: cc.Node = null;

    @property(cc.Node)
    dieMain: cc.Node = null;

    @property(cc.Node)
    dieMainSub: cc.Node = null;

    @property(cc.Node)
    mainFriend: cc.Node = null;

    @property(cc.Node)
    mainFriendContain: cc.Node = null;
    
    @property(cc.Sprite)
    dieHead: cc.Sprite = null;

    @property(cc.Label)
    dieStep: cc.Label = null;

    @property(cc.Camera)
    mainCamera: cc.Camera = null;

    list: [] = [];
    list2 = {};

    PAGE = 0;
    PAGE_SIZE = 5;

    posInit: cc.Vec2 = null;

    mainRankItemsPool: cc.NodePool = null;

    onLoad() {
        this.mainRankItemsPool = new cc.NodePool(MainRankItem)
        this.posInit = this.mainFriendContain.getPosition()
    }

    start () {
        let self = this
        wx.onMessage(data => {
            switch (data.text) {
                case 'score':
                    self.submit(data.value)
                    break
                case 'show':
                    self.mainNode.removeAllChildren()
                    self.rankMain.active = true
                    self.dieMain.active = false
                    self.mainFriend.active = false
                    self.setMyInfo(function(res,s){
                        self.setFriendRank(res,s)
                    })
                    break
                case 'close':
                    self.rankMain.active = false
                    self.dieMain.active = false
                    self.mainFriend.active = false
                    break
                case 'next':
                    self.next()
                    break
                case 'pre':
                    self.pre()
                    break
                case 'die':
                    self.rankMain.active = false
                    self.dieMain.active = true
                    self.mainFriend.active = false
                    self.myInfo = data.value.myInfo
                    self.die(data.value.score)
                    break
                case 'mainFriend':
                    // self.rankMain.active = false
                    // self.dieMain.active = false
                    // self.mainFriend.active = true
                    // self.spawnMainRankItem(data.value)
                    break
                case 'mainFriendReset':
                    // self.mainFriendContain.setPosition(self.posInit)
                    // for(let i = this.mainFriendContain.childrenCount - 1; i >= 0; i --) {
                    //     this.mainRankItemsPool.put(this.mainFriendContain.children[i])
                    // }
                    break
                case 'mainFriendMove':
                    // self.mainFriendContain.runAction(cc.moveBy(data.value.duration,cc.v2(-data.value.distance,0)))
                    break
            }
        })

        wx.getFriendCloudStorage({
            keyList:['jump12_score'],
            success: function (list) {
                if(list.data && list.data.length!=0){
                    this.list = this.sortList(list.data,false)
                    // for(let obj of this.list) {
                    //     let val = (obj.KVDataList && obj.KVDataList[0] && obj.KVDataList[0].value) || -1
                    //     if (val != -1){
                    //         this.list2[val] = obj
                    //     }
                    // }
                }
            }.bind(this),
            fail: function (res) {
                console.error('res : error info == ', res)
            }
        })
    }

    spawnMainRankItem(d) {
        if (this.list2[d.score]){
            let gold = null
            if (this.mainRankItemsPool.size() > 0) {
                gold = this.mainRankItemsPool.get(this)
            } else {
                gold = cc.instantiate(this.mainInfoPrefab)
            }
            this.mainFriendContain.addChild(gold)
            gold.setPosition(d.x,0)
            gold.getComponent(MainRankItem).init(this)
            gold.getComponent(MainRankItem).setData(this.list2[d.score])
        }
    }

    despawnMainRankItem(node: cc.Node) {
        this.mainRankItemsPool.put(node)
    }

    getScoreByIndex(index: number): number {
        let obj = this.list[index]
        return (obj.KVDataList && obj.KVDataList[0] && obj.KVDataList[0].value) || 0
    }
 
    die(curScore: number) {
        this.dieMainSub.active = false
        let firstScore = 0
        if (this.list && this.list.length != 0){
            firstScore = this.getScoreByIndex(0)
        }
        //这次分数比排行榜最高分数还要高就不显示即将超越
        if (curScore >= firstScore) {
          return;
        }
        let userDataList = this.list
        if (userDataList.length == 0) {
          return;
        }
      
        let beyondIndex = -1
        let openid = this.myInfo.openid
        if (userDataList.length == 1) {
          if (userDataList[0].openid != openid) {
            if (curScore > this.getScoreByIndex(0)) {
              beyondIndex = 0
            }
          }
        } else {
          for (var i = userDataList.length - 1; i >= 0; i--) {
            if (userDataList[i].openid != openid) {
              if (curScore < this.getScoreByIndex(i)) {
                beyondIndex = i
                break
              }
            //   else if (curScore > this.getScoreByIndex(i) && curScore < this.getScoreByIndex(i - 1)) {
            //     beyondIndex = i - 1
      
            //     if (beyondIndex >= 1){
            //       if (userDataList[beyondIndex].openid == openid) {
            //         beyondIndex = beyondIndex - 1;
            //       }
            //     }else{
            //       if (userDataList[beyondIndex].openid != openid) {
            //       }
            //     }
                
            //     break;
            //   }
            }
          }
          if (beyondIndex == -1){
              return
          }
        }
      
        let obj = this.list[beyondIndex]

        if (obj.KVDataList && obj.KVDataList[0] && obj.KVDataList[0].value)
            this.dieStep.string = obj.KVDataList[0].value + ''
        let self = this
        try {
            let image = wx.createImage();
            image.onload = () => {
                try {
                    let texture = new cc.Texture2D();
                    texture.initWithElement(image);
                    texture.handleLoadedTexture();
                    self.dieHead.spriteFrame = new cc.SpriteFrame(texture);
                } catch (e) {
                    console.log(e)
                    self.dieHead.node.active = false;
                }
            }
            image.src = obj.avatarUrl;
        }
        catch (e) {
            console.log(e)
            this.dieHead.node.active = false;
        }
        this.dieMainSub.active = true
    }

    submit(score) {
        wx.getUserCloudStorage({
            keyList:['jump12_score'],
            success: function(getres){
                var bestScore = 0
                if(getres.KVDataList && getres.KVDataList.length!=0 && getres.KVDataList[0].value){
                    bestScore = getres.KVDataList[0].value
                }
                if(score > bestScore){
                    wx.setUserCloudStorage({
                        KVDataList:[{
                            key: 'jump12_score',
                            value: score + ''
                        }],
                        success: function(r) {
                            
                        },
                        fail: function(r) {
                            console.log(r)
                        }
                    })
                }
            },
            fail: function(r) {
                console.log(r)
            }
        })
    }

    setFriendRank(res,score) {
        let data = res.data[0]
        wx.getFriendCloudStorage({
            keyList:['jump12_score'],
            success: function (list) {
                if(list.data && list.data.length!=0){
                    list = this.sortList(list.data,false)
                    for(var i = 0; i < list.length; i ++) {
                        list[i].rank = i + 1
                        if (data && data.nickName && data.avatarUrl && data.nickName == list[i].nickname && data.avatarUrl == list[i].avatarUrl 
                            && list[i].KVDataList && list[i].KVDataList.length != 0 && list[i].KVDataList[0].value == score) {
                            this.myNode.getComponent('RankItem').setData(list[i])
                        }
                        // let val = (list[i].KVDataList && list[i].KVDataList[0] && list[i].KVDataList[0].value) || -1
                        // if (val != -1){
                        //     this.list2[val] = list[i]
                        // }
                    }
                    
                    this.list = list
                    this.PAGE = 1
                    this.loadPage()
                }
            }.bind(this),
            fail: function (res) {
                console.error('res : error info == ', res)
            }
        })
    }

    loadPage() {
        let pageStart = (this.PAGE - 1) * this.PAGE_SIZE
        let pagedData = this.list.slice(pageStart, pageStart + this.PAGE_SIZE)
        this.mainNode.removeAllChildren()
        for(let i = 0, len = pagedData.length; i < len; i++)
        {   
            let node = cc.instantiate(this.itemNode)
            node.getComponent('RankItem').setData(pagedData[i])
            this.mainNode.addChild(node);
        }
    }

    next() {
        if (this.PAGE < Math.ceil(this.list.length/this.PAGE_SIZE)) {
            this.PAGE ++
            this.loadPage()
        }
    }

    pre() {
        if (this.PAGE > 1) {
            this.PAGE --
            this.loadPage()
        }
    }

    myInfo = {
        openid: ''
    };
    setMyInfo(cb: Function) {
        let self = this
        wx.getUserInfo({
            openIdList:['selfOpenId'],
            lang: 'zh_CN',
            success: (res) => {
                self.myNode.getComponent('RankItem').setData(res.data[0])
                wx.getUserCloudStorage({
                    keyList:['jump12_score'],
                    success: function(getres){
                        if(getres.KVDataList){
                            if(getres.KVDataList.length && getres.KVDataList.length!=0){
                                self.myNode.getComponent('RankItem').setData(getres)
                                if (cb) {
                                    cb(res,getres.KVDataList[0].value)
                                }
                                return
                            }
                        }
                        if (cb) {
                            cb(res,-1)
                        }
                    },
                    fail: function() {
                        if (cb) {
                            cb(res,-1)
                        }
                    }
                })
            },

            fail: (res) => {
                if (cb) {
                cb(null,-1)
            }
            }
        })
    }

    sortList(ListData, order): []{ //排序(ListData：res.data;order:false降序，true升序)
        ListData.sort(function(a,b){
            var AMaxScore = 0;
            var KVDataList = a.KVDataList;
            for(var i = 0; i < KVDataList.length;i++){
                if(KVDataList[i].key == "jump12_score"){
                AMaxScore = KVDataList[i].value;
                }
            }
    
            var BMaxScore = 0;
            KVDataList = b.KVDataList;
            for(var i = 0; i<KVDataList.length; i++){
                if(KVDataList[i].key == "jump12_score"){
                BMaxScore = KVDataList[i].value;
                }
            }
    
            if(order){
                return AMaxScore - BMaxScore;
            }else{
                return BMaxScore - AMaxScore;
            }
        });
        return ListData;
    }
}
